<template>
  <!-- 页面-组织架构 -->
  <div class="orgStructure-page page-box-row-left padding-20">
    <!-- -----------------组织部分----------------- -->
    <!-- 组织架构 -->
    <FormBlock class="orgStructure" :title="$t('module.orgManage.search')" direction="column" style="width: 28%">
      <!-- 搜索 -->
      <!-- <Input
        search
        v-model.trim="searchDeptValue"
        :placeholder="$t('module.orgManage.searchOrg')"
        clearable
        class="search-box"
        @on-enter="_getOrgTreeList()"
        @on-clear="_getOrgTreeList()"
      />-->
      <AutoComplete
        style="margin: auto; display: block"
        v-model="nameOrCode"
        @on-search="remoteSearch"
        @on-select="selsectOrg"
        @on-clear="clearSearch"
        :placeholder="$t('module.treeManage.warning.enterNodeNameCode')"
        icon="md-search"
        clearable
      >
        <Option v-for="(option, index) in searchResult" :value="option" :key="index">{{ option }}</Option>
        <p class="complete-more get-complete-more" v-if="searchResult.length >= 10 && isShowMore" @click="showMore">
          {{ $t('common.showMore') }}
        </p>
      </AutoComplete>
      <!-- 树 -->
      <el-tree
        style="margin-top: 0; padding: 6px 12px"
        :data="baseData"
        lazy
        :default-expanded-keys="expandedKeys"
        :load="loadData"
        :props="defaultProps"
        highlight-current
        check-strictly
        :indent="16"
        node-key="orgId"
        ref="orgTree"
        icon-class="ivu-icon-ios-arrow-forward"
        @node-click="handleNodeClick"
        :render-content="renderContent"
        :expand-on-click-node="false"
      ></el-tree>
    </FormBlock>
    <!-- 组织信息 -->
    <FormBlock
      class="orgInformation"
      :title="$t('module.orgManage.orgInformation')"
      direction="column"
      v-if="showDetail"
    >
      <!-- <div class="operate-wrapper">
        <CommonImportExport :configs="importExportConfigs"></CommonImportExport>
      </div> -->

      <div class="content-box">
        <div class="content">
          <Form class="org" ref="orgForm" :model="form" :rules="rules" label-position="right" :label-width="82">
            <div class>
              <Row :gutter="32" class="code-row-bg">
                <!-- 组织编码 -->
                <Col span="11">
                  <Form-item prop="orgCode" :label="$t('module.orgManage.orgCode')">
                    <Input
                      v-model="form.orgCode"
                      :placeholder="$t('module.orgManage.pleaseInput')"
                      :disabled="form.orgId != ''"
                      v-bind:readonly="canNotBeEdit"
                      @on-blur="blur"
                    ></Input>
                  </Form-item>
                </Col>
                <!-- 组织名称 -->
                <Col span="11">
                  <Form-item prop="lang" :label="$t('module.orgManage.orgName')">
                    <!-- <Input v-model="form.orgName" :placeholder="$t('module.orgManage.pleaseInput')"></Input>
                    <Icon class="global-icon" @click.native="orgNameLang"></Icon>-->
                    <LangInput ref="orgNameInput" v-model="form.lang"></LangInput>
                  </Form-item>
                </Col>
              </Row>
              <Row :gutter="32" class="code-row-bg">
                <!-- 组织类型 -->
                <Col span="11">
                  <Form-item prop="orgType" :label="$t('module.orgManage.orgType')">
                    <Select v-model="form.orgType" :disabled="form.orgId != ''">
                      <Option v-for="item in orgTypeOption" :value="item.value" :key="item.value">{{
                        item.label
                      }}</Option>
                    </Select>
                  </Form-item>
                </Col>
                <!-- 关联公司 -->
                <Col span="11">
                  <Form-item prop="relationCompany" :label="$t('module.orgManage.relationCompany')">
                    <Input
                      v-model="form.companyName"
                      :placeholder="$t('module.orgManage.pleaseSelect')"
                      :disabled="true"
                    ></Input>
                    <RPButton optType="reset" :text="$t('module.orgManage.select')" @click="selectRelationCompany" />
                  </Form-item>
                </Col>
              </Row>
              <Row :gutter="32" class="code-row-bg">
                <!-- 排序号 -->
                <Col span="11">
                  <Form-item prop="orderNo" :label="$t('module.orgManage.sortId')">
                    <InputNumber
                      style="width: 100%"
                      :min="0"
                      :max="99"
                      v-model="form.orderNo"
                      :placeholder="$t('module.orgManage.pleaseInput')"
                    ></InputNumber>
                  </Form-item>
                </Col>
                <!-- 状态 -->
                <Col span="11">
                  <Form-item prop="status" :label="$t('common.status')">
                    <RadioGroup v-model="form.enabled">
                      <Radio :label="1">{{ $t('common.valid') }}</Radio>
                      <Radio :label="0">{{ $t('common.invalid') }}</Radio>
                    </RadioGroup>
                  </Form-item>
                </Col>
              </Row>
              <Row :gutter="32" class="code-row-bg">
                <!-- 组织路径 -->
                <Col span="11">
                  <Form-item prop="orgPath" :label="$t('module.orgManage.orgPath')">
                    <Input v-model="form.orgPathName" placeholder :disabled="true" :readonly="true"></Input>
                  </Form-item>
                </Col>
              </Row>
              <Row :gutter="32" class="code-row-bg">
                <!-- 描述 -->
                <Col span="22">
                  <Form-item prop="orgDesc" :label="$t('module.orgManage.orgDesc')">
                    <Input type="textarea" :rows="4" :maxlength="100" v-model="form.orgDesc" placeholder></Input>
                  </Form-item>
                </Col>
              </Row>
              <!-- <Row :gutter="32" class="code-row-bg" style="margin-right: -106px">
                <Col span="20" style="text-align: right">
                  <Form-item prop="button"> -->
              <!-- 组织 - 保存/修改 -->
              <!-- <RPButton :loading="saveLoading" :text="$t('common.save')" optType="save" @click="saveOrUpdateOrg" />
                  </Form-item>
                </Col>
              </Row> -->
            </div>
          </Form>
          <!-- 主数据信息 -->
          <div style="margin-bottom: 10px">
            <CommonUserData
              ref="CommonUserData"
              :showPlaceholder="false"
              :disabled="true"
              dataType="org"
              :showMainData="true"
              :userInfo="mainInfo"
            ></CommonUserData>
          </div>
          <!-- 拓展属性 -->
          <div style="margin-bottom: 10px">
            <FormCreate
              :templateId.sync="form.attributeContext"
              templateType="ORG"
              :attributeValue="form.attributeValue"
              :fApi.sync="fApi"
              :options="fcOption"
              isClearable
              :selectWidth="'358px'"
            />
          </div>
          <!-- -----------------部门部分----------------- -->
          <div class="dept" v-if="form.orgId">
            <p class="deptTitle">{{ $t('module.orgManage.distributionDept') }}</p>
            <div class="deptContent">
              <!-- 搜索 -->
              <!-- <Form
                :model="searchForm"
                class="ivu-form-no-margin-bottom"
                :label-width="13"
                ref="deptForm"
                @submit.native.prevent
              >
                <Row :gutter="16">
                  <Col span="11">
                    <Form-item prop="orgName">
                      <Input
                        type="text"
                        v-model.trim="searchForm.orgName"
                        :placeholder="$t('module.orgManage.searchDept')"
                        @on-enter="searchDeptTreeData"
                      ></Input>
                    </Form-item>
                  </Col>
                  <Col span="6" class="handle-bar-one">
                    <Form-item prop="button">
                      <div>
                        <RPButton optType="search" @click="searchDeptTreeData" />
                        <RPButton optType="reset" @click="resetDeptTreeData" />
                      </div>
                    </Form-item>
                  </Col>
                </Row>
              </Form>-->
              <!-- 表格 -->
              <!-- <div>
                <el-table
                  lazy
                  :data="tableData"
                  style="width: 98%; margin: 0 auto;"
                  row-key="orgId"
                  :tree-props="{ children: 'childrenDept', hasChildren: 'hasChildren' }"
                  :load="getChildrenDep"
                >
                  <el-table-column prop="orgCode" :label="$t('module.orgManage.deptCode')"></el-table-column>
                  <el-table-column prop="orgName" :label="$t('module.orgManage.deptName')"></el-table-column>
                  <el-table-column prop="orderNo" :label="$t('module.orgManage.sortId')" width="120"></el-table-column>
                  <el-table-column :label="$t('common.status')" width="120">
                    <template slot-scope="scope">
                      <StatusButton
                        :status="scope.row.enabled == 1 ? '0' : '1'"
                      >{{ scope.row.enabled == 1 ? $t("common.enable") : $t("common.disable") }}</StatusButton>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('module.orgManage.operation')" width="120">
                    <template slot-scope="scope">
                      <RowTools :data="RowToolsData(scope)" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>-->
            </div>
          </div>
          <org-department ref="department" :orgInfo="form" v-if="form.orgId"></org-department>
        </div>
        <div class="bottom">
          <RPButton :loading="saveLoading" :text="$t('common.save')" optType="save" @click="saveOrUpdateOrg" />
        </div>
      </div>
    </FormBlock>
  </div>
</template>

<script>
let pathArr = []
import {
  searchOrgTree,
  getOrgTreeList,
  updateOrgNode,
  addOrgNode,
  getDeptTreeList,
  searchDeptTree,
  getLang,
  getCompany,
  getMainDataByOrgid
} from '@/api/orgApi.js'
import publicApi from '@/api/public.js'
import locales from '../locales.js'
import { searchDelayTime } from '@/const.js'
import SelectCompany from './SelectCompany.vue'
import OrgNameEdit from './OrgNameEdit.vue'

import NewDepartment from './NewDepartment.vue'
import positionInfo from './positionInfo.vue'
import OrgDepartment from './OrgDepartment.vue'
import CommonUserData from '@/components/common/mainUserInfo/CommonUserData'
import FormCreate from '@/components/common/FormCreate'
import CommonImportExport from '@/components/import-and-export/index.vue'

export default {
  name: 'org-structure',
  mixins: [locales],
  components: {
    OrgDepartment,
    CommonUserData,
    FormCreate,
    CommonImportExport,
  },
  data() {
    // -----------------组织部分-----------------
    // 组织编码-不符合字段规则的错误提示
    const validateOrgCode = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验

      if (value == null || value === '') {
        callback(new Error(this.$t('module.orgManage.enterCode')))
      } else if (value.length > 32) {
        callback(new Error(this.$t('common.warning.codeCheckLength')))
      } else if (!new RegExp('^([a-zA-Z0-9]|_|-|\\.)+$').test(value)) {
        callback(new Error(this.$t('module.orgManage.codeContain')))
      } else if (new RegExp('[\u4e00-\u9fa5]').test(value)) {
        callback(new Error(this.$t('common.warning.codeCheckCharacter')))
      }
      callback()
    }
    // 组织名称-不符合字段规则的错误提示
    const validateOrgName = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验

      if (value == null || value === '') {
        callback(new Error(this.$t('module.orgManage.enterName')))
      } else if (value != value.trim()) {
        callback(new Error(this.$t('module.orgManage.noBalnk')))
      } else if (value.length > 100) {
        callback(new Error(this.$t('module.orgManage.nameMaxFifty')))
      }
      callback()
    }
    // 组织类型-不符合字段规则的错误提示
    const validateOrgType = (rule, value, callback) => {
      if (value == null || value === '') {
        callback(new Error(this.$t('module.orgManage.enterType')))
      }
      callback()
    }
    // 排序号-不符合字段规则的错误提示
    const validateOrderNo = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验

      if (value == null || value === '') {
        callback(new Error(this.$t('module.orgManage.enterOrderNo')))
      }
      callback()
    }
    // 描述-不符合字段规则的错误提示
    const validateOrgDesc = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验

      if (value != null && value != value.trim() && value.trim() === '') {
        callback(new Error(this.$t('module.orgManage.enterLegalDesc')))
      }
      if (value != null && value.length > 1000) {
        callback(new Error(this.$t('module.orgManage.descMaxTH')))
      }
      callback()
    }
    const nameValidater = (rule, value, callback) => {
      let flag = value.filter(item => {
        if (item.value == '') {
          return true
        }
      })
      if (flag.length > 0 || value.length == 0) {
        callback(new Error(this.$t('module.orgManage.enterName')))
      } else {
        callback()
      }
    }
    return {
      // -----------------组织树-----------------
      nameOrCode: '',
      expandedKeys: [],
      orgList: [],
      query: {
        orgPath: '',
        orgTypeFilter: 1
      },
      isShowMore: false,
      pageNum: 1,
      // -----------------组织部分-----------------
      userInfo: '', //角色
      tenantCode: '', //当前租户编码
      // 搜索部分------------
      searchDeptValue: '', //搜索组织
      searchResult: [], // 搜索下拉框展示的节点名称数据
      searchResultNode: [], // 搜索下拉框的节点所有数据
      pressCount: 0,
      // 树------------
      // 绑定的数据
      form: {
        orgCode: '', //组织编码
        orgName: [], //组织名称
        orgType: 2, //组织类型
        companyId: '', //关联公司
        companyName: '', //关联公司
        orderNo: 1, //排序号
        enabled: '', //状态
        orgPath: '', //组织路径
        orgPathName: '', //组织路径名
        orgDesc: '', //组织描述
        orgId: '',
        parentId: '',
        version: '',
        tenantCode: '', //租户编码
        lang: [],
        attributeContext: '',
        attributeValue: {}
      },
      // 主数据信息
      mainInfo: {},
      searchForm: { orgName: '' },
      baseData: [],
      defaultProps: {
        children: 'childrenDept',
        label: 'orgName'
      },
      node: {},
      // nodeElement: {},
      // 编辑表单------------
      // 字段规则
      rules: {
        lang: [{ validator: nameValidater, trigger: 'change', required: true }],
        orgCode: [{ validator: validateOrgCode, trigger: 'blur', required: true }],
        // orgName: [{ validator: validateOrgName, trigger: "blur", required: true }],
        orgType: [{ validator: validateOrgType, trigger: 'blur', required: true }],
        orderNo: [{ validator: validateOrderNo, trigger: 'blur', required: true }],
        orgDesc: [{ validator: validateOrgDesc, trigger: 'blur' }]
      },
      isReadOnly: true,
      saveLoading: false, //保存的加载效果
      showDetail: false,
      orgTypeOption: [
        {
          label: this.$t('module.orgManage.group'),
          value: 1
        },
        {
          label: this.$t('module.orgManage.company'),
          value: 2
        }
      ],
      // -----------------部门部分-----------------
      // 搜索
      deptPressCount: 0,
      // 表格数据
      tableData: [],
      fApi: null,
      embedSvg: orgType => {
        let svgUrl
        switch (+orgType) {
          case 1:
            svgUrl = 'static\\images\\enterprise.svg'
            break
          case 2:
            svgUrl = 'static\\images\\company.svg'
            break
          case 10:
            svgUrl = 'static\\images\\department.svg'
            break
          default:
            svgUrl = ''
        }
        return svgUrl
      }
    }
  },
  computed: {
    canNotBeEdit: function () {
      if (this.isReadOnly) {
        return true
      }
      return false
    },
    fcOption() {
      return {
        global: {
          '*': {
            col: {
              span: 12
            },
            props: {
              width: '355px'
            }
          }
        },
        form: {
          labelWidth: 100,
          size: 'default'
        }
      }
    },
    importExportConfigs() {
      const apiPrefix = window?.RPConfig?.mgt || ''
      const queryTemplateParams = {
        requestPath: `${apiPrefix}/template/list`,
        requestMethod: 'post',
        requestParams: {
          templateCategory: 'ORG'
        }
      }
      return [
        {
          type: 'import',
          btnText: '导入',
          requestPath: `${apiPrefix}/organization/importExcel`,
          successCallback: () => {
            this._getOrgTreeList()
          }
        },
        {
          type: 'export',
          btnText: '导出',
          requestPath: `${apiPrefix}/organization/listExport`,
          requestMethod: 'get',
          requestParams: {
            orgPath: this?.form?.orgPath || '' // 父组织路径
          }
        },
        {
          type: 'export',
          btnText: '下载组织模板',
          exportType: 'downloadTemplate',
          requestPath: `${apiPrefix}/organization/excelTemplateExport`,
          requestMethod: 'get',
          requestParams: {
            attributeTemplateId: ''
          },
          queryTemplateParams
        }
      ]
    }
  },
  created: function () {
    this.init()
    this._getOrgTreeList()
  },
  mounted: function () {},
  methods: {
    loadData(node, resolve) {
      if (node.level == 0) {
        // 隐藏根节点
        return
      }
      // 是叶子节点不进行查询
      if (node.isLeaf) {
        resolve([])
      }
      publicApi.queryOrg({ orgPath: node.data.orgPath, orgTypeFilter: 1 }).then(children => {
        resolve(children)
      })
    },
    debounce(fn, wait = 300) {
      if (this.fun !== null) {
        clearTimeout(this.fun)
      }
      this.fun = setTimeout(fn, wait)
    },
    // 搜索结果大于10条，点击查看更多
    showMore() {
      this.getSelectNode(this.nameOrCode)
    },
    getSelectNode(value) {
      // 点击查看更多，pageNum改为2，从第二页开始查询
      this.pageNum++
      if (value && value.indexOf('/') == -1) {
        let param = {
          condition: {
            nameOrCode: value,
            orgTypeFilter: 1
          },
          pageNum: this.pageNum,
          pageSize: 10
        }
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            if (data.records.length > 0) {
              this.loading = false
              let pathArr = []
              let orgArr = []
              const list = data.records.map(item => {
                pathArr.push(item.orgNameFullPath)
              })

              orgArr = data.records

              this.$nextTick(() => {
                this.searchResult = this.searchResult.concat(pathArr)
                this.orgList = this.orgList.concat(orgArr)
              })
              if (data.pages == this.pageNum) this.isShowMore = false
            } else {
              // 查询结果，data.records为空数组时，隐藏查看更多按钮
              this.isShowMore = false
            }
          })
          .catch(err => {
            this.loading = false
          })
      }
    },
    // 根据组织树编码和名称搜索
    remoteSearch(value) {
      this.debounce(() => {
        this.getListOrganizationPaths(this.nameOrCode)
      }, 300)
    },
    getListOrganizationPaths(value) {
      this.pageNum = 1 // 当重新搜索时，默认从第一页开始查询
      this.isShowMore = true // 当重新搜索时，默认显示查看更多
      // this.searchResult = []; //数组中只包含orgNameFullPath
      this.orgList = [] // 数组中包含orgId orgNameFullPath orgName orgPath
      this.searchResultNode = []
      let param = {
        condition: {
          nameOrCode: value,
          orgTypeFilter: 1
        },
        pageNum: 1,
        pageSize: 10
      }
      if (value !== '') {
        this.loading = true
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            this.searchResult = []
            this.loading = false
            const list = data.records.map(item => {
              this.searchResult.push(item.orgNameFullPath)
            })

            this.orgList = data.records
            if (data.pages == this.pageNum) this.isShowMore = false
          })
          .catch(err => {
            this.loading = false
          })
      } else {
        this.orgList = []
      }
    },
    selsectOrg(value) {
      this.expandedKeys = []
      this.$refs.orgTree.store.lazy = false
      let data = this.orgList.filter(item => {
        if (item.orgNameFullPath == value) {
          this.expandedKeys.push(item.orgId)
          return item.orgId
        }
      })
      let selectOrg = data[0]
      publicApi
        .getTreeBySelectOrg({ orgId: selectOrg.orgId, orgTypeFilter: 1 })
        .then(data => {
          this.baseData = data
          this.$nextTick(() => {
            this.$refs['orgTree'].setCurrentKey(this.expandedKeys[0])

            this.form.orgCode = selectOrg.orgCode
            this.form.orgPath = selectOrg.orgPath
            this.form.orgPathName = selectOrg.orgNameFullPath
            this.form.orgType = selectOrg.orgType
            this.form.orderNo = selectOrg.orderNo
            this.form.enabled = selectOrg.enabled
            this.form.orgDesc = selectOrg.orgDesc
            this.form.companyId = selectOrg.companyId
            this.form.orgId = selectOrg.orgId
            this.form.parentId = selectOrg.parentId
            this.form.attributeContext = selectOrg.attributeContext
            this.form.attributeValue = selectOrg
            //获取关联公司
            getCompany({ ids: [selectOrg.companyId] }).then(res => {
              this.form.companyName = res.data[0].companyName
            })
            getLang(selectOrg.orgId).then(res => {
              this.form.lang = res.data
            })
            getMainDataByOrgid({ orgId: selectOrg.orgId }).then(res => {
              this.mainInfo = res.data || {}
            })
            // this._getDeptTreeList({ deptId: this.form.orgId });
          })
        })
        .catch(err => {
          this.loading = false
        })
    },
    // // 点击清空按钮
    clearSearch() {
      this.searchResult = []
      this.searchResultNode = []
      this.expandedKeys = []
      this.nameOrCode = ''
      this.$refs.orgTree.store.lazy = true
      this._getOrgTreeList()
    },
    // -----------------部门部分-----------------
    // 表格操作列的icon
    RowToolsData(scope) {
      return [
        {
          type: 'icon',
          icon: 'md-create',
          text: this.$t('module.orgManage.editDept'),
          handle: () => {
            this.newDept('dept', 'edit', scope.row)
          }
        },
        {
          type: 'icon',
          icon: 'md-add',
          text: this.$t('module.orgManage.newDept'),
          handle: () => {
            this.newDept('dept', 'new', scope.row)
          }
        },
        {
          type: 'icon',
          icon: 'ios-person',
          text: this.$t('module.orgManage.positionAmanagement'),
          handle: () => {
            new this.$sidelipPage(positionInfo, {
              props: {
                departmentInfo: {
                  tenantCode: this.tenantCode, //租户编码
                  department: scope.row
                }
              }
            })
          }
        }
      ]
    },
    resetDeptTreeData() {
      // this.$refs["deptForm"].resetFields();
      this.searchDeptTreeData()
    },
    searchDeptTreeData() {
      let param = {
        nameOrCode: this.searchForm.orgName,
        deptId: this.form.orgId
      }

      // this._getDeptTreeList(param);
    },
    // 新建部门
    newDept(idx, newOrEdit, row) {
      if (!this.form.orgId) {
        this.$message.error({
          content: this.$t('module.orgManage.enterOrg'),
          duration: 3
        })
        return
      }
      this.deptNodeData = row
      // 父组织路径
      let parentOrgPath = row ? row.orgPath : this.form.orgPath
      // idx:org代表是在组织下新建根部门节点，dept代表是在根部门下新建子部门节点
      //新建根部门：在组织下新建根部门，currentOrgId、parentId都为当前选中的组织树节点id
      //新建子部门：在根部门下新建子部门，currentOrgId为当前选中的组织树节点id、parentId为当前选中的根部门树节点id
      new this.$pageModal(
        NewDepartment,
        {
          props: {
            // tenantCode: "0000"
            orgInfo: {
              idx: idx,
              newOrEdit: newOrEdit,
              row: newOrEdit == 'edit' ? row : {},
              tenantCode: this.tenantCode, //租户编码
              currentOrgId: this.form.orgId,
              orgPath: parentOrgPath,
              parentId: idx == 'org' ? this.form.orgId : row.orgId
            }
          }
        },
        data => {
          if (data) {
            this.$refs.department.getDeptTreeList()
            // if (data.newOrEdit == "new") {
            //   this._getDeptTreeList({ deptId: this.form.orgId });
            // } else if (data.newOrEdit == "edit") {
            //   this.jsonObjectCopy(row, data.data);

            // }
          }
        }
      )
    },
    // -----------------组织部分-----------------
    // 查询租户编码
    init() {
      this.userInfo = $store.state['ripples-components'].userInfo
      if (!this.userInfo) return
      // 根据当前角色查询租户编码
      this.tenantCode = this.userInfo.tenantCode
    },

    // Tree：树节点的内容区的渲染 Function，Function(h, { node, data, store }
    renderContent(h, { node, data, store }) {
      return (
        <span class="tree-item-box">
          <embed src={this.embedSvg(data.orgType)} width="10" height="10" type="image/svg+xml" class="node-svg" />
          <span class="node-label" title={node.label}>
            {node.label}
          </span>
          <span class="orgEditMenu" id={'MENU' + data.orgId}>
            <span class="orgEditSonMenu" on-click={event => this.addOrg(event, false, node, data)}>
              <i class="el-icon-plus" title={this.$t('module.orgManage.addOrg')}></i>
            </span>
          </span>
        </span>
      )
    },
    // Tree：节点被点击时的回调
    handleNodeClick(data, node, nodeElement) {
    
      //获取关联公司
      if (data.companyId) {
        getCompany({ ids: [data.companyId] }).then(res => {
          this.form.companyName = res.data[0].companyName
        })
      }
      getLang(data.orgId).then(res => {
        this.form.lang = res.data || []
      })
      getMainDataByOrgid({ orgId: data.orgId }).then(res => {
        this.mainInfo = res.data || {}
      })
      this.node = node
      this.showDetail = true

      this.jsonObjectCopy(this.form, data)
      // 清除校验信息
      this.$refs["orgForm"].validate();

      // 获取树列表详情
      // this._getDeptTreeList({ deptId: this.form.orgId });
      // 清除部门输入框内容
      this.deptSearchValue = ''
      // 拼接组织路径
      let allPathNodes = this.getAllPathNodes(node)
      this.form.orgPath = ''
      this.form.orgPathName = ''
      allPathNodes.forEach(node => {
        if (this.form.orgPath) {
          this.form.orgPath = this.form.orgPath + '/' + node.orgCode
          this.form.orgPathName = this.form.orgPathName + '/' + node.orgName
        } else {
          this.form.orgPath = node.orgCode
          this.form.orgPathName = node.orgName
        }
      })
    },
    // 默认获取所有节点、点击获取下一级节点
    _getOrgTreeList(orgId, resolve) {
      // getOrgTreeList({ nameOrCode: this.searchDeptValue }).then(response => {
      //   let data = response.data;
      //   console.log(data);
      //   if (orgId) {
      //     resolve(data);
      //   } else {
      //     this.baseData = data;
      //     //默认选中第一个节点，不加nextTick的话，this.baseData刚有数据，树节点还没渲染完，导致默认选中第一个节点的样式不生效

      //     this.$nextTick(() => {
      //       this.selectFirstOrg();
      //     });
      //   }
      // });

      publicApi.queryOrg(this.query).then(data => {
        this.baseData = data
        this.$nextTick(function () {
          this.selectFirstOrg()
          this.$refs.orgTree.store.lazy = true
        })
      })
    },

    // 第一个选中的节点
    selectFirstOrg() {
      if (this.baseData.length > 0) {
        let firstOrgInfo = this.baseData[0]
        let { orgId, orgCode, orgName, companyId, companyName } = firstOrgInfo
        getLang(orgId).then(res => {
          this.form.lang = res.data
        })
        getMainDataByOrgid({ orgId: orgId }).then(res => {
          this.mainInfo = res.data || {}
        })
        // 当前行加选中效果
        this.$refs['orgTree'].setCurrentKey(orgId)
        this.showDetail = true
        //初始化this.form对象
        Object.assign(this.form, this.initParam())
        // 获取树列表详情
        this.form.orgPath = orgCode
        this.form.orgPathName = orgName
        // this.$nextTick(() => {
          // this._getDeptTreeList({ deptId: orgId });
          this.jsonObjectCopy(this.form, firstOrgInfo)
        // })
        //获取关联公司
        if (companyId) {
          getCompany({ ids: [companyId] }).then(res => {
            this.form.companyName = res.data[0].companyName
          })
        }
      }
    },
    // 拷贝,如果source里存在target相同的key，将source的数据替换给target
    jsonObjectCopy(target, source) {
      //只拷贝target中存在的key
      let targetKeys = Object.keys(target)
      for (const key in targetKeys) {
        if (source.hasOwnProperty(targetKeys[key])) {
          target[targetKeys[key]] = source[targetKeys[key]]
        }
      }
      // this.form.attributeContext = source?.attributeContext || ''
      this.form.attributeValue = source || {}
    },
    blur() {
      // 替换最后一个 / 后面的路径
      let lastIndex = this.form.orgPath.lastIndexOf('/')
      this.form.orgPath = this.form.orgPath.substr(0, lastIndex) + '/' + this.form.orgCode
    },
    // Tree：树节点的添加
    addOrg(event, addTopOrg, node, data) {
      // this.isGetLang = false;
      // getLang(node.data.orgId).then(res => {
      //   this.form.lang = [];
      //   this.isGetLang = true;
      // });
      this.form.lang = []

      event.stopPropagation() //阻止点击事件向上冒泡
      this.node = node
      this.isReadOnly = false
      let parentId = ''
      parentId = this.node.data.orgId
      this.showDetail = true
      this.jsonObjectCopy(this.form, this.initParam())
      this.form.parentId = parentId
      // 获取部门树列表
      this.$refs['orgForm'].resetFields()
      // this._getDeptTreeList({ deptId: "" });
      // 当前行加选中效果
      this.$refs['orgTree'].setCurrentKey(parentId)
      this.$nextTick(() => {
        this.form.orgCode = ''
      })
      // 拼接组织路径
      let allPathNodes = this.getAllPathNodes(node)
      this.form.orgPath = null
      this.form.orgPathName = null
      allPathNodes.forEach(node => {
        if (this.form.orgPath) {
          this.form.orgPath = this.form.orgPath + node.orgCode + '/'
          this.form.orgPathName = this.form.orgPathName + node.orgName + '/'
        } else {
          this.form.orgPath = node.orgCode + '/'
          this.form.orgPathName = node.orgName + '/'
        }
      })
    },
    getAllPathNodes(node) {
      if (node.level == 1) {
        // 当前是根节点
        return [node.data]
      } else {
        // 当前非根节点
        let arr = this.getAllPathNodes(node.parent)
        arr.push(node.data)
        return arr
      }
    },
    // 初始化提交参数
    initParam() {
      let param = {
        orgCode: '', //组织编码
        orgName: '', //组织名称
        orgDesc: '', //组织描述
        orgId: '',
        parentId: '',
        version: '0',
        orderNo: 1, //排序号
        enabled: 1, //状态
        orgPath: '', //组织路径
        orgType: 2, //组织类型
        companyId: '', //关联公司
        companyName: '', //关联公司
        tenantCode: '', //租户编码
        lang: [],
        attributeValue: {},
        attributeContext: ''
      }
      return param
    },
    // 保存
    saveOrUpdateOrg() {
      if (!this.form.lang) {
        return
      }
      this.organizationLangVos = this.form.lang
      this.$nextTick(() => {
        this.$refs['orgForm'].validate(valid => {
          if (valid) {
            if (this.fApi && this.fApi.formData) {
              this.fApi.validate(valid => {
                if (valid) {
                  this.form.attributeValue = this.fApi.formData();
                  this.onSubmit()
                }
              });
            } else {
              this.onSubmit()
            }
          } else {
            this.$message.error(this.$t('common.formValidateFailed'))
          }
        })
      })
    },
    onSubmit() {
      const newFormData = {};
      if (this?.fApi?.formData) {
        const formData = this.fApi.formData();
        const rules = this.fApi.rule;
        for (const r of rules) {
          newFormData[r.matchColumn] = r.type === 'checkbox'
            ? JSON.stringify(formData[r.field])
            : formData[r.field];
        }
      }
      // 参数
      let param = Object.assign({}, this.initParam(), newFormData)
      param.organizationLangVos = this.form.lang
      let mainInfo = this.$refs['CommonUserData'].getInfo()
      this.form = { ...this.form, ...mainInfo }
      this.jsonObjectCopy(param, this.form)
      if (this.form.orgId) {
        // 修改树节点的接口
        updateOrgNode(param)
          .then(response => {
            this.$message.success({
              content: this.$t('module.orgManage.editSuccess'),
              duration: 3
            })
            if (!!this.node.data) {
              this.jsonObjectCopy(this.node.data, param)
              this.node.data.version = this.form.version //更新数据版本号
            }
            this.saveLoading = false
            this.clearSearch()
            this.init()
            this._getOrgTreeList()
          })
          .catch(data => {
            this.saveLoading = false
          })
      } else {
        // 新增树节点的接口
        addOrgNode(param)
          .then(response => {
            //此处更新组织
            this.$message.success({
              content: this.$t('module.orgManage.addSuccess'),
              duration: 3
            })
            param.orgId = response.data
            this.form.orgId = param.orgId
            //创建child子功能并初始化数据
            let child = this.initParam()
            this.jsonObjectCopy(child, param)
            Object.assign(child, {
              children: []
            })
            if (this.baseData.length == 0) {
              this.baseData.push(child)
            } else {
              this.append(this.node.store, this.node.data, child)
            }
            this.saveLoading = false
            this.init()
            this.clearSearch()
            this._getOrgTreeList()
            this.clearSearch()
          })
          .catch(data => {
            this.saveLoading = false
          })
      }
    },
    // Tree：添加 为 Tree 中的一个节点追加一个子节点（没看）
    append(store, data, sonData) {
      store.append(sonData, data)
      let orgTree = this.$refs['orgTree']
      orgTree.setCurrentKey(sonData.orgId)
      this.node = orgTree.getCurrentNode()
    },
    // 点击-填写多语言
    orgNameLang() {
      new this.$pageModal(OrgNameEdit, {
        props: {
          orgId: this.form.orgId
        }
      })
    },
    // 点击-选择关联公司
    selectRelationCompany() {
      new this.$pageModal(
        SelectCompany,
        {
          props: {
            // tenantCode: "0000"
            tenantCode: this.tenantCode
          }
        },
        data => {
          if (data) {
            this.form.companyId = data.id
            this.form.companyName = data.companyName
          }
        }
      )
    }
  },
  watch: {
    nameOrCode: {
      handler(value) {
        if (!value) {
          this.searchResult = []
          this.clearSearch()
        }
      },
      deep: true
    },
    'form.lang': function (newVal, oldVal) {
      this.$nextTick(() => {
        if (this.$refs['orgNameInput'] && this.$refs['orgNameInput'].langCodeValue) {
          if (this.form.orgPathName.indexOf('/') == -1) {
            // 当前是根节点
            this.form.orgPathName = this.$refs['orgNameInput'].langCodeValue
          } else {
            // 当前是子节点
            let lastIndex = this.form.orgPathName.lastIndexOf('/')
            this.form.orgPathName =
              this.form.orgPathName.substr(0, lastIndex) + '/' + this.$refs['orgNameInput'].langCodeValue
          }
        }
      })
    }
  }
}
</script>
<style lang="less">
.orgStructure-page {
  .search-box {
    width: 94%;
    margin: auto auto 10px;
    display: block;
  }
  // .dept-table-box {
  // display: flex;
  // flex-direction: column;
  // align-items: center;
  // }
  // 组织架构
  height: 100%;
  .orgStructure {
    .ivu-select-dropdown {
      max-height: 330px !important;
      .ivu-select-dropdown-list {
        width: fit-content;
        .ivu-select-item:hover {
          background: #fff !important;
        }
      }
    }
    .ivu-select {
      width: 94% !important;
    }
    .node-svg {
      position: relative;
      top: 1px;
    }
    .node-label {
      margin-left: 3px;
      display: inline-block;
      // width: calc(~"100% - 46px");
      width: 80%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  // 组织信息
  .orgInformation {
    .block-body {
      overflow: initial;
    }
    // 组织
    .org {
      .ivu-row:nth-child(1) {
        .ivu-col:nth-child(2) {
          .ivu-form-item {
            .ivu-form-item-content {
              .ivu-icon {
                font-size: 22px;
                color: #ff6f4b;
              }
            }
          }
        }
      }
      .ivu-row:nth-child(2) {
        .ivu-col:nth-child(2) {
          .ivu-form-item {
            .ivu-form-item-content {
              display: flex;
              .ivu-btn {
                padding: 3px 9px;
                margin-left: 10px;
              }
            }
          }
        }
      }
      .ivu-row:nth-child(6) {
        .ivu-col {
          .ivu-btn {
            background-color: #ff6f4b;
            border-color: #ff6f4b;
          }
          .ivu-btn:nth-child(1) {
            margin-right: 14px;
          }
        }
      }
    }
    // 部门
    .dept {
      .deptTitle {
        font-size: 14px;
        height: 46px;
        line-height: 46px;
        padding-left: 10px;
        background-color: #f5f5f5;
      }
      .deptContent {
        margin: 10px 0;
        .ivu-select {
          margin-bottom: 10px;
        }
        .el-table {
          .el-table__header-wrapper {
            thead {
              tr {
                th {
                  background: #f5f5f5 !important;
                }
              }
            }
          }
        }
      }
    }
  }
  .el-tree .is-current>.el-tree-node__content {
    .el-icon-plus:hover {
      background: var(--primary-color-opacity2);
    }
  }
  .tree-item-box {
    position: relative;
    width: 93% !important;
    display: flex;
    align-items: center;
    line-height: 32px;
    .orgEditMenu {
      position: absolute;
      right: 10px;
      top: -2px;
      .el-icon-plus {
        padding: 2px;
        border-radius: 3px;
        font-size: 14px;
        font-weight: bold;
        &:hover {
          background: var(--tree-content-hover-icon-bg);
        }
      }
    }
  }
}
.content-box {
  height: 100%;
  .content {
    height: calc(100% - 50px);
    overflow-x: hidden;
    overflow-y: auto;
  }
  .content::-webkit-scrollbar {
    width: 4px;
  }
  .bottom {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 22px;
    height: 46px;
  }
}
.operate-wrapper {
  padding: 0 8px 10px 8px;
  .ivu-btn {
    margin-right: 8px;
  }
}
</style>
